package com.avoscloud.chat.ui.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.example.studycard.R;
import com.avoscloud.chat.adapter.UserFriendAdapter;
import com.avoscloud.chat.base.App;
import com.avoscloud.chat.entity.SortUser;
import com.avoscloud.chat.service.AddRequestService;
import com.avoscloud.chat.service.CacheService;
import com.avoscloud.chat.service.UserService;
import com.avoscloud.chat.service.chat.IM;
import com.avoscloud.chat.ui.activity.AddFriendActivity;
import com.avoscloud.chat.ui.activity.ChatActivity;
import com.avoscloud.chat.ui.activity.GroupConvListActivity;
import com.avoscloud.chat.ui.activity.NewFriendActivity;
import com.avoscloud.chat.ui.view.ClearEditText;
import com.avoscloud.chat.ui.view.EnLetterView;
import com.avoscloud.chat.ui.view.HeaderLayout;
import com.avoscloud.chat.ui.view.xlist.XListView;
import com.avoscloud.chat.util.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ContactFragment extends BaseFragment implements
		OnItemClickListener, OnItemLongClickListener, OnClickListener,
		XListView.IXListViewListener {
	private static CharacterParser characterParser;
	private static PinyinComparator pinyinComparator;
	private ClearEditText clearEditText;
	private TextView dialog;
	private XListView friendsList;
	private EnLetterView rightLetter;
	private UserFriendAdapter userAdapter;
	private List<SortUser> friends = new ArrayList<SortUser>();
	private HeaderLayout headerLayout;
	private ImageView msgTipsView;
	private LinearLayout newFriendLayout, groupLayout;
	private IM im;
	private boolean hidden;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.contact_fragment, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		characterParser = CharacterParser.getInstance();// 创建单例，java汉字转为拼音
		pinyinComparator = new PinyinComparator();
		im = IM.getInstance();
		initHeader();
		initListView();
		initRightLetterView();
		initEditText();
		onRefresh();
	}

	// 导入所需布局，设置标题导航栏等图标
	private void initHeader() {
		headerLayout = (HeaderLayout) getView().findViewById(R.id.headerLayout);
		headerLayout.showTitle(App.ctx.getString(R.string.contact));
		headerLayout.showRightImageButton(
				R.drawable.base_action_bar_add_bg_selector,
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						Utils.goActivity(ctx, AddFriendActivity.class);
					}
				});
	}

	/*
	 * 模糊查找好友 CharSequence是一个接口，代表有序字符集合，可读可写序列
	 */
	private void initEditText() {
		clearEditText = (ClearEditText) getView().findViewById(
				R.id.et_msg_search);
		clearEditText.addTextChangedListener(new SimpleTextWatcher() {
			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i2,
					int i3) {
				filterData(charSequence.toString());
			}
		});
	}

	/*
	 * 若输入框内无输入，则显示全部好友，若输入框清空，则updata
	 * Adapter并显示全部好友（userAdapter.updateDatas(friends);）
	 * 若输入框内有输入，则遍历全部好友找出相匹配的好友并显示
	 */
	private void filterData(String filterStr) {
		if (TextUtils.isEmpty(filterStr)) {
			userAdapter.updateDatas(friends);
		} else {
			List<SortUser> filterDateList = new ArrayList<SortUser>();
			filterDateList.clear();
			for (SortUser sortModel : friends) {
				String name = sortModel.getInnerUser().getUsername();
				if (name != null
						&& (name.contains(filterStr) || characterParser
								.getSelling(name).startsWith(filterStr))) {
					filterDateList.add(sortModel);
				}
			}
			// 将符合条件的好友按首字母大写排列并局部刷新显示
			Collections.sort(filterDateList, pinyinComparator);
			userAdapter.updateDatas(filterDateList);
		}
	}

	// 根据首字母对好友进行分类，实现字母索引查找好友
	private List<SortUser> convertAVUser(List<AVUser> datas) {
		List<SortUser> sortUsers = new ArrayList<SortUser>();
		int total = datas.size();
		for (int i = 0; i < total; i++) {
			AVUser avUser = datas.get(i);
			SortUser sortUser = new SortUser();
			sortUser.setInnerUser(avUser);
			String username = avUser.getUsername();
			if (username != null) {
				// 将用户名转为汉语拼音，若本身是英文直接一个个加入到字符串生成器，若是中文则需先转成ASCII码，在对应到汉语拼音
				String pinyin = characterParser.getSelling(username);
				String sortString = pinyin.substring(0, 1).toUpperCase();// 获取首字母并将其转为大写
				if (sortString.matches("[A-Z]")) {// 若是以A-Z的字母开头，则按A-Z进行分类，否则都归于#
					sortUser.setSortLetters(sortString.toUpperCase());
				} else {
					sortUser.setSortLetters("#");
				}
			} else {
				sortUser.setSortLetters("#");
			}
			sortUsers.add(sortUser);
		}
		Collections.sort(sortUsers, pinyinComparator);// 根据A-Z进行排序源数据
		return sortUsers;
	}

	// 下拉刷新上拉加载
	private void initListView() {
		friendsList = (XListView) getView().findViewById(R.id.list_friends);
		friendsList.setPullRefreshEnable(true);
		friendsList.setPullLoadEnable(false);
		friendsList.setXListViewListener(this);
		LayoutInflater mInflater = LayoutInflater.from(ctx);
		// 导入头部布局
		RelativeLayout headView = (RelativeLayout) mInflater.inflate(
				R.layout.contact_include_new_friend, null);
		msgTipsView = (ImageView) headView.findViewById(R.id.iv_msg_tips);// 新朋友红点提示图片
		newFriendLayout = (LinearLayout) headView.findViewById(R.id.layout_new);
		groupLayout = (LinearLayout) headView.findViewById(R.id.layout_group);

		newFriendLayout.setOnClickListener(this);
		groupLayout.setOnClickListener(this);

		friendsList.addHeaderView(headView);// 将头部布局加入到朋友列表中，可以进行同步刷新
		userAdapter = new UserFriendAdapter(getActivity(), friends);
		friendsList.setAdapter(userAdapter);
		friendsList.setOnItemClickListener(this);
		friendsList.setOnItemLongClickListener(this);
		// 设置实时监听触点坐标
		friendsList.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Utils.hideSoftInputView(getActivity());// 若触碰屏幕则隐藏输入框
				return false;
			}
		});
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		if (isVisibleToUser) {
			// refreshMsgsFromDB();
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	// 生成右边字母序列，以便按字母进行索引
	private void initRightLetterView() {
		rightLetter = (EnLetterView) getView().findViewById(R.id.right_letter);
		dialog = (TextView) getView().findViewById(R.id.dialog);
		rightLetter.setTextView(dialog);// 跳出所选字母的弹框提示
		rightLetter
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
	}

	// 若点击新朋友则跳转到新朋友界面，若点击群组则跳转到群组界面
	@Override
	public void onClick(View v) {
		int viewId = v.getId();
		if (viewId == R.id.layout_new) {
			Utils.goActivity(ctx, NewFriendActivity.class);
		} else if (viewId == R.id.layout_group) {
			Utils.goActivity(ctx, GroupConvListActivity.class);
		}
	}

	@Override
	public void onRefresh() {
		new NetAsyncTask(ctx, false) {
			boolean haveAddRequest;//判断是否有添加请求
			List<AVUser> friends1;

			@Override
			protected void doInBack() throws Exception {
				haveAddRequest = AddRequestService.hasAddRequest();//是否有新的好友请求，true则有
				friends1 = UserService.findFriends();
				CacheService.registerUsers(friends1);
				CacheService.setFriendIds(AVOSUtils.getObjectIds(friends1));
			}

			@Override
			protected void onPost(Exception e) {
				friendsList.stopRefresh();
				if (e != null) {
					Utils.toast(ctx, e.getMessage());
				} else {
					msgTipsView.setVisibility(haveAddRequest ? View.VISIBLE
							: View.GONE);
					List<SortUser> sortUsers = convertAVUser(friends1);
					ContactFragment.this.friends = Collections
							.unmodifiableList(sortUsers);
					userAdapter.updateDatas(sortUsers);
				}
			}
		}.execute();
	}

	@Override
	public void onLoadMore() {
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		this.hidden = hidden;
		if (!hidden) {
			onRefresh();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!hidden) {
			onRefresh();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		SortUser user = (SortUser) arg0.getAdapter().getItem(position);
		ChatActivity.goByUserId(getActivity(), user.getInnerUser()
				.getObjectId());
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int position, long arg3) {
		// TODO Auto-generated method stub
		SortUser user = (SortUser) arg0.getAdapter().getItem(position);
		showDeleteDialog(user);
		return true;
	}

	public void showDeleteDialog(final SortUser user) {
		new AlertDialog.Builder(ctx)
				.setMessage(R.string.deleteContact)
				.setPositiveButton(R.string.sure,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								deleteFriend(user);
							}
						}).setNegativeButton(R.string.cancel, null).show();
	}

	private void deleteFriend(final SortUser user) {
		final ProgressDialog dialog = Utils.showSpinnerDialog(getActivity());
		UserService.removeFriend(user.getInnerUser().getObjectId(),
				new SaveCallback() {
					@Override
					public void done(AVException e) {
						dialog.dismiss();
						if (Utils.filterException(e)) {
							onRefresh();
						}
					}
				});
	}

	private class LetterListViewListener implements
			EnLetterView.OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(String s) {
			int position = userAdapter.getPositionForSection(s.charAt(0));
			if (position != -1) {
				friendsList.setSelection(position);
			}
		}
	}
}
